package com.baidu.iit.pxp.listener;

import com.baidu.iit.pvm.ActivityIllegalArgumentException;
import com.baidu.iit.pvm.delegate.DelegateExecution;
import com.baidu.iit.pvm.delegate.DelegateInvocation;
import com.baidu.iit.pvm.delegate.ExecutionListener;
import com.baidu.iit.pxp.delegate.ClassDelegate;
import com.baidu.iit.pxp.delegate.Expression;
import com.baidu.iit.pxp.delegate.JavaDelegate;
import com.baidu.iit.pxp.invocation.ExecutionListenerInvocation;
import com.baidu.iit.pxp.invocation.JavaDelegateInvocation;
import com.baidu.iit.pxp.model.FieldDeclaration;

import java.util.List;

/**
 * User: huangweili
 * Date: 14-4-30
 * Time: 下午3:52
 */
public class DelegateExpressionExecutionListener implements ExecutionListener {

    protected Expression expression;
    private final List<FieldDeclaration> fieldDeclarations;

    public DelegateExpressionExecutionListener(Expression expression, List<FieldDeclaration> fieldDeclarations) {
        this.expression = expression;
        this.fieldDeclarations = fieldDeclarations;
    }

    public void notify(DelegateExecution execution) throws Exception {
        Object delegate = expression.getValue(execution);
        ClassDelegate.applyFieldDeclaration(fieldDeclarations, delegate);

        if (delegate instanceof ExecutionListener) {
            DelegateInvocation invocation = new ExecutionListenerInvocation((ExecutionListener) delegate, execution);
            invocation.proceed();
        } else if (delegate instanceof JavaDelegate) {
            DelegateInvocation invocation = new JavaDelegateInvocation((JavaDelegate) delegate, execution);
            invocation.proceed();
        } else {
            throw new ActivityIllegalArgumentException("Delegate expression " + expression
                    + " did not resolve to an implementation of " + ExecutionListener.class
                    + " nor " + JavaDelegate.class);
        }
    }


    public String getExpressionText() {
        return expression.getExpressionText();
    }

}
